#!/bin/bash
# thmar 编译脚本
# Optional Command Arguments:
#        ONLYBUILD 不执行 cmake 创建工程只编译版本
# Optional Environment Variables: 
#        BUILD_TYPE 编译版本类型(DEBUG|RELEASE),默认 DEBUG
#        BUILD_PRJ 为 ON 时编译版本
#        RELEASE_PRJ 为 ON 时编译并 release 版本
# Xcode 编译方式
# G=Xcode ./gnu_build.sh

#字符串转大写
#参数1：字符串
function string_toupper()
{
    echo $1 | tr '[a-z]' '[A-Z]'
}
#字符串转小写
#参数1：字符串
function string_lower()
{
    echo $1 | tr '[A-Z]' '[a-z]'
}

sh_folder=$(cd "$(dirname $0)"; pwd -P)
folder_name=$(basename $sh_folder) 
# 定义编译的版本类型(debug|release)
build_type=release
[[ "$(string_lower $BUILD_TYPE)" =~ debug|release ]] && build_type=$(string_lower ${BUILD_TYPE})

# 是否编译测试和工具程序
build_test=ON

# 默认cmake -G 生成的工程文件类型
[ -z "$G" ] && G="Eclipse CDT4 - Unix Makefiles"

BUILD_PRJ=ON
echo build_type=$build_type

# 执行 cmake 创建工程
create_prj=ON
while [[ $# -gt 0 ]]
do
# 转大写
key=$(string_toupper ${1})
case $key in
ONLYBUILD)
	create_prj=OFF;BUILD_PRJ=ON;shift;;
*) shift;;
esac
done

machine=$(g++ -dumpmachine)
gcc_version=$(g++ -dumpversion) 

so_suffix=so
[[ "$machine" =~ .+darwin.+ ]] && so_suffix=dylib

# 安装路径, 默认安装到脚本所在目录的 release 目录下
# 如果指定了 PREFIX 环境变量, 则安装到该目录下
install_prefix=$sh_folder/release/thmar-$machine
[ -n "$PREFIX" ] && install_prefix="$PREFIX"

# 编译路径
[ -n "$PROJECT_FOLDER" ] && prj_folder="$PROJECT_FOLDER"
[ -z "$PROJECT_FOLDER" ] && prj_folder=$sh_folder/../thmar-$machine.prj
[[ "$(string_toupper ${RELEASE_PRJ})" =~ ON ]] && prj_folder=$sh_folder/build/thmar-$machine

echo =========================================================================
echo       Configuration: thmar $machine:$build_type
echo     Build Directory: $prj_folder
echo   Install Directory: $install_prefix
echo =========================================================================

if [[ "$(string_toupper ${create_prj})" =~ ON ]]
then
	[ -d $prj_folder ] && rm -fr $prj_folder
	mkdir -p $prj_folder || exit 

	pushd $prj_folder || exit

	# conan 安装依赖库
	conan install "$sh_folder"  -s build_type=${build_type^} -of $prj_folder \
		-o with_paho=True -o build_test=True \
		--build missing || exit
	echo "creating Project for $machine ..."
	cmake "$sh_folder" -G "$G" -DCMAKE_BUILD_TYPE=$(string_toupper $build_type)\
		-DCMAKE_TOOLCHAIN_FILE=./conan_toolchain.cmake \
		-DCMAKE_INSTALL_PREFIX=$install_prefix \
		-DCMAKE_SH="CMAKE_SH-NOTFOUND" -DCMAKE_POLICY_DEFAULT_CMP0091="NEW"\
		
		
else
	pushd $prj_folder || exit
fi

if [[ "$(string_toupper ${RELEASE_PRJ})" =~ ON ]] || [[ "${BUILD_PRJ})" =~ ON ]]
then
	cmake --build . --config $build_type --target install -- -j 8 || exit 
fi

popd

